package com.shop.service.impl;

import com.github.pagehelper.PageInfo;
import com.shop.entity.User;
import com.shop.exception.GlobalException;
import com.shop.mapper.UserMapper;
import com.shop.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

/**
 * @author XCH
 * @date 2025 - 05 - 19
 */
@Service("userService")
@RequiredArgsConstructor
@Transactional(rollbackFor = RuntimeException.class,
        propagation = Propagation.REQUIRED)
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    public PageInfo<User> listUser(Integer page, Integer limit) {
        List<User> list = userMapper.listUser(page, limit);
        return new PageInfo<>(list);
    }
    @Override
    public User userLogin(String username, String password) {
        return userMapper.userLogin(username, password);
    }

    @Override
    public void addUser(User user) {
        try {
            userMapper.addUser(user);
        }catch (Exception e){
            throw new GlobalException(400, "添加用户失败");
        }
    }

    @Override
    public void deleteUser(Integer id) {
        try {
            userMapper.deleteUser(id);
        }catch (Exception e){
            throw new GlobalException(400, "删除用户失败");
        }
    }

    @Override
    public void updateUser(User user) {
        try {
            userMapper.updateUser(user);
        }catch (Exception e){
            throw new GlobalException(400, "更新用户失败");
        }

    }

    @Override
    public void updateImage(Integer id, String image) {
        try {
            userMapper.updateImage(id, image);
        }catch (Exception e){
            throw new GlobalException(400, "更新用户头像失败");
        }
    }

    @Override
    public void updateNickname(Integer id, String nickname) {
        try {
            userMapper.updateNickname(id, nickname);
        }catch (Exception e){
            throw new GlobalException(400, "更新用户昵称失败");
        }
    }

    @Override
    public void updateEmail(Integer id, String email) {
        try {
            userMapper.updateEmail(id, email);
        }catch (Exception e){
            throw new GlobalException(400, "更新用户邮箱失败");
        }
    }

    @Override
    public void updateSex(Integer id, String sex) {
        try {
            userMapper.updateSex(id, sex);
        }catch (Exception e){
            throw new GlobalException(400, "更新用户性别失败");
        }
    }

    @Override
    public void updateUsername(Integer id, String username) {
        try {
            userMapper.updateUsername(id, username);
        }catch (Exception e){
            throw new GlobalException(400, "更新用户用户名失败");
        }
    }

    @Override
    public User SelectByUserId(Integer id) {
        try {
            return userMapper.SelectByUserId(id);
        }catch (Exception e){
            throw new GlobalException(400, "查询用户失败"+e.getMessage());
        }
    }

    @Override
    public User selectByEmail(String email) {
        userMapper.selectByEmail(email);

        User user = userMapper.selectByEmail(email);
        if (user == null) {
            user = new User();
            user.setEmail(email);
            user.setNickname("用户_" + generateRandomString(4));
            user.setUsername("user_" + generateRandomString(6));
            user.setPassword(generateSecurePassword(12));
            user.setRole("USER");
            user.setImage("default.png");
            user.setCreateTime(LocalDateTime.now());
            user.setSex("男");
            user.setPhone(generateRandomPhoneNumber());
            System.out.println("USER："+ user);
            userMapper.addUser(user); // 插入数据库
        }
        return user;
    }

    @Override
    public int countUser() {
        try {
            return userMapper.countUser();
        }catch (Exception e){
            throw new GlobalException(400, "查询用户失败"+e.getMessage());
        }
    }

    @Override
    public User selectByUsername(String username) {
        try  {
            return userMapper.selectByUsername(username);
        }catch (Exception e){
            throw new GlobalException(400, "查询用户失败"+e.getMessage());
        }
    }

    @Override
    public void updateUserPassword(Integer id, String password) {
        try {
            userMapper.updateUserPassword(id, password);
        }catch (Exception e){
            throw new GlobalException(400, "更新用户密码失败"+e.getMessage());
        }
    }

    @Override
    public void updateUserPhone(Integer id, String phone) {
        try {
            userMapper.updateUserPhone(id, phone);
        }catch (Exception e){
            throw new GlobalException(400, "更新用户手机号失败"+e.getMessage());
        }
    }

    /**
     * 生成指定长度的随机字符串（字母+数字）
     */
    private String generateRandomString(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * chars.length());
            sb.append(chars.charAt(index));
        }
        return sb.toString();
    }

    /**
     * 生成11位随机手机号
     */
    private static final String[] VALID_PREFIXES = {
            // 中国移动
            "134", "135", "136", "137", "138", "139",
            "150", "151", "152", "157", "158", "159",
            "182", "183", "184", "187", "188", "195",
            // 中国联通
            "130", "131", "132", "155", "156", "166",
            "185", "186", "176", "196",
            // 中国电信
            "133", "153", "180", "181", "189", "191",
            "193", "199", "173", "177"
    };

    public static String generateRandomPhoneNumber() {
        Random random = new Random();
        // 随机选择一个有效号段
        String prefix = VALID_PREFIXES[random.nextInt(VALID_PREFIXES.length)];
        StringBuilder phone = new StringBuilder(prefix);

        // 生成剩余8位数字
        for (int i = 0; i < 8; i++) {
            int digit = random.nextInt(10);
            phone.append(digit);
        }

        return phone.toString();
    }
    private String generateSecurePassword(int length) {
        String lowerChars = "abcdefghijklmnopqrstuvwxyz";
        String upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String digits = "0123456789";
        String specialChars = "!@#$%^&*()-_=+[]{}|;:,.<>?/";
        String allChars = lowerChars + upperChars + digits + specialChars;

        StringBuilder password = new StringBuilder();

        // 确保至少各有一个小写、大写、数字和特殊字符
        password.append(getRandomChar(lowerChars));
        password.append(getRandomChar(upperChars));
        password.append(getRandomChar(digits));
        password.append(getRandomChar(specialChars));

        // 剩余字符随机填充
        for (int i = 4; i < length; i++) {
            password.append(getRandomChar(allChars));
        }

        // 打乱顺序，避免开头是固定模式
        return shuffleString(password.toString());
    }

    /**
     * 从指定字符串中随机选取一个字符
     */
    private char getRandomChar(String str) {
        int index = (int) (Math.random() * str.length());
        return str.charAt(index);
    }

    /**
     * 打乱字符串顺序
     */
    private String shuffleString(String input) {
        char[] chars = input.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            int randomIndex = (int) (Math.random() * chars.length);
            char temp = chars[i];
            chars[i] = chars[randomIndex];
            chars[randomIndex] = temp;
        }
        return new String(chars);
    }

}
